<template>
  <div class="wrap">
    <div class="approval-process">
      <div class="approval-header">
        <div class="approval-process-content" v-if="state.data.length > 0">
          <a-timeline>
            <a-timeline-item :color="item.activityType == 'endEvent' ? 'gray' : item.activityType == 'startEvent' ? 'green' : index === state.data.length - 1 ? 'blue' : 'green'" v-for="(item, index) in state.data" :key="index">
              <p class="time">{{ item.startTime }}</p>
              <div class="title">
                {{ item.activityType == 'endEvent' ? '结束' : item.activityName }}
              </div>
              <p class="first" v-if="item.approvalType">
                <span v-if="item.nrOfInstances > 1">{{ item.nrOfInstances }}人{{ item.approvalType == 1 ? '会签' : '或签' }}</span>
                <span v-if="item.nrOfInstances === 1">
                  {{ item.participantInfos[0].assigneeName }}
                </span>
                <span v-if="item.outcome == 1 && item.participantInfos[0]?.assigneeId!=='AUTO_PASS_ASSIGNEE'">（同意）</span>
                <span v-if="item.outcome == 2">（拒绝）</span>
                <span v-if="item.outcome == 3">（退回）</span>
             <div class="btn-container">
                  <a-button class="btn" type="primary" v-if="item.activityType === 'userTask' && !item.outcome&& isShowRemoveBtn(item.participantInfos)" @click="handleChange(item)">转交审核</a-button>
                  <a-button class="btn" type="danger" v-if="item.activityType === 'userTask' && !item.outcome && isShowRemoveBtn(item.participantInfos)" @click="handleRemove(item)">移除审核</a-button>
             </div>
              </p>
              <div class="other" v-if="item.nrOfInstances > 1" v-for="(subItem, idx) in item.participantInfos" :key="idx">
                <p :class="{ first: !item.approvalType }" v-if="idx === 0">
                  <span>{{ subItem.assigneeName }}</span>
                  <span v-if="subItem.outcome == 1">（同意）</span>
                  <span v-if="subItem.outcome == 2">（拒绝）</span>
                  <span v-if="subItem.outcome == 3"> 退回 {{ subItem.targetActivityName ? `至${subItem.targetActivityName}` : '' }}</span>
                  <!-- <span v-if="!item.approvalType" class="time">{{ item.startTime }}</span> -->
                </p>
                <p v-if="idx !== 0">
                  <span>{{ subItem.assigneeName }}</span
                  ><span v-if="subItem.outcome == 1">（同意）</span>
                  <span v-if="subItem.outcome == 2">（拒绝）</span>
                  <span v-if="subItem.outcome == 3">（退回）</span>
                </p>
                <p v-if="subItem.comment">（审批意见：{{ subItem.comment }}）</p>
              </div>
            </a-timeline-item>
          </a-timeline>
        </div>
      </div>
      <div class="approval-bottom">
        <a-button @click="handleBack">返回</a-button>
      </div>
    </div>
    <div ref="dialog">
      <a-modal :getContainer="()=>$refs.dialog" title="转交审核" v-model:visible="changeModalVisible" :key="modalKey" :footer="null">
        <DynamicForm :questions="formQuestions" :config="config" ref="modalFormRef">
          <template #selectPerson="{ question }">
            <div @click="handleClickSelect(question)">
              <a-select style="pointer-events: none" v-model:value="question.value" placeholder="请选择">
                <a-select-option :key="item.id" :label="item.name || item.nickName" :value="item.id" v-for="item in memberList">{{ item.name || item.nickName }}</a-select-option>
              </a-select>
            </div>
          </template>
        </DynamicForm>
      </a-modal>
     </div>
    <select-personnel @save="save" @cancel="cancel" v-if="personalModalVisible" :visible="personalModalVisible"></select-personnel>
  </div>
</template>

<script setup lang="ts">
import { reactive, computed, ref, getCurrentInstance, onMounted, watch, onUnmounted, createVNode, toRaw, nextTick } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ExclamationCircleOutlined } from '@ant-design/icons-vue';
import { Form, message, Modal } from 'ant-design-vue';
import SelectPersonnel from './components/selectPersonnel.vue';
import { filter } from 'rxjs/operators';
import { Subscription } from 'rxjs';
import { DYNAMICLAYERCLEAR, DYNAMICLAYERFORM, LOCALSUBSERVE } from '@/mixins/subject/subject-types';
import DynamicForm from '@/components/public-template/DynamicForm/dynamic-form/dynamic-form.component.vue';
import indexService from './index.service';
import { formInfoStore } from '@/store/modules/form';

const { proxy }: any = getCurrentInstance();
const formStore = formInfoStore();

let $subscribeSub: Subscription;
const route = useRoute();
const router = useRouter();

const state = reactive({
  data: [],
  xmlData: ''
});
const modalFormRef = ref(null);
const changeModalVisible = ref(false);
const modalKey = ref(0);
const personalModalVisible = ref(false);
const memberList = ref([]);
const handleClickSelect = (data: any) => {
  personalModalVisible.value = true;
};
const cancel = () => {
  personalModalVisible.value = false;
};
const save = (data: any) => {
  if (data.data.length === 0) {
    message.error('请选择！');
    return;
  }
  memberList.value = data.data;
  const res =
    data.data.map((v: any) => {
      return v.id;
    }) || [];
  if (res?.length > 1) {
    message.error('只能选择一个');
    cancel();
  } else {
    formStore.setQuestions(formStore.questions, {
      assignee: res?.[0]
    });
    nextTick(() => {
      modalFormRef.value?.initVerify();
    });
    cancel();
  }
};

//查询 审批流程列表 流程图
const getActivitiesList = () => {
  const params = {
    processInstanceId: route.query?.processInstanceId
  };
  proxy.$Http.api('flowable/process/instance/list/activities', params, 'post').then((res) => {
    if (res?.success) {
      state.data = res.data?.activities || [];
      state.xmlData = res.data?.xml;
    }
  });
};
onMounted(() => {
  subWatchForm();
  subWatchPub();
  nextTick(() => {
    init();
  });
});
onUnmounted(() => {
  if ($subscribeSub != undefined) {
    $subscribeSub.unsubscribe();
  }
  proxy.$NotificationFormSub.clearParams();
  proxy.$NotificationPubSub.clearParams();
});
const subWatchForm = () => {
  $subscribeSub = proxy.$NotificationFormSub
    .getParams()
    .pipe(filter((res: any) => res !== 0))
    .subscribe(async (item: any) => {
      try {
        console.log(item, 'item');
        if (item.key === LOCALSUBSERVE && item.state.name === 'flowChangePerson') {
        }
        if (item.key === DYNAMICLAYERCLEAR) {
          changeModalVisible.value = false;
        }
      } catch (err) {
        /* empty */
      }
    });
};
const subWatchPub = () => {
  $subscribeSub = proxy.$NotificationPubSub
    .getParams()
    .pipe(filter((res: any) => res !== 0))
    .subscribe(async (item: any) => {
      try {
        if (item.key === DYNAMICLAYERCLEAR) {
          changeModalVisible.value = false;
          getActivitiesList();
        }
      } catch (err) {
        /* empty */
      }
    });
};
const init = () => {
  getActivitiesList();
};
const handleBack = () => {
  proxy?.$parentRouter.push({ name: 'ApproveManageSummary' })
};
const handleRemove = (data: any) => {
  Modal.confirm({
    title: '确定移除此审批人？',
    icon: createVNode(ExclamationCircleOutlined),
    autoFocusButton: null,
    okText: '确定',
    cancelText: '取消',
    onOk() {
      const params = {
        processInstanceId: route.query?.processInstanceId,
        activityId: data.activityId
      };
      proxy.$Http.api('flowable/process/instance/audit/remove', params, 'post').then((res) => {
        if (res?.success) {
          message.success('移除成功！');
          getActivitiesList();
        }
      });
    },
    onCancel() {},
    class: 'test'
  });
};
const config: any = ref({
  updateUrl: 'flowable/process/instance/handover',
  width: '760px',
  name: 'flowChangePerson',
  layout: 'vertical',
  cancelSave: false,
  // localSub: true,
  rowKey: 'key', // 唯一标识
  okText: '确认',
  type: 'layer',
  btnPosition: 'center',
  grid: 24,
  labelCol: 24,
  combinationMethod: (data: any) => {
    data.activityId = activityId.value;
    data.processInstanceId = route.query.processInstanceId;
    return data;
  }
});
formStore.setQuestions(reactive(indexService.getQuestions()));
let formQuestions: any = reactive(formStore.getQuestions);
const activityId = ref('');
const handleChange = (data: any) => {
  activityId.value = data.activityId;
  changeModalVisible.value = true;
  modalKey.value++;
};
const isShowRemoveBtn = (list) => {
  let flag = true;
  if (list?.length === 0) {
    flag = false;
  }
  list.map((item: any) => {
    if (item?.assigneeId === 'AUTO_PASS_ASSIGNEE') {
      flag = false;
    }
  });
  return flag;
};
</script>

<style lang="less" scoped>
.wrap {
  // padding: 20px;
  // background-color: #f0f2f5;
  position: relative;

  .approval-process {
    margin-top: 20px;
    background-color: #ffffff;
    position: relative;
    min-height: 400px;
    display: flex;
    flex-direction: column;
    .approval-header {
      padding: 10px 22px;
      flex: 1;
      h4 {
        font-weight: 600;
        font-size: 18px;
        line-height: 18px;
        height: 20px;
        padding-left: 10px;
        margin-bottom: 20px;
        margin-top: 20px;
        border-left: 4px solid #005aea;
        position: relative;
      }
    }

    .approval-process-content {
      padding-left: 10px;
      margin-top: 20px;
      .title {
        margin-top: 5px;
        margin-bottom: 5px;
        height: 26px;
        font-size: 18px;
        font-family: PingFangSC, PingFang SC;
        font-weight: 500;
        color: rgba(0, 0, 0, 0.85);
        line-height: 26px;
      }
      .time {
        font-size: 16px;
        color: rgba(0, 0, 0, 0.65);
        }
      :deep(.ant-timeline-item-head-blue) {
      border-color: #005aea;
      }
      :deep(.ant-timeline-item-head-green) {
      border-color: #52c41a;
      }
      :deep(.ant-timeline-item-head-gray) {
      border-color: rgba(0,0,0,0.25);
      }
      .first {
        overflow: hidden;
        font-size: 16px;
        font-family: PingFangSC, PingFang SC;
        font-weight: 400;
        color: rgba(0, 0, 0, 0.45);
      }
      .btn-container {
        display: inline-block;
        position: absolute;
        left: 25%;
        top: 0;
      }
      .btn {
        margin-left: 20px;
        height: 100%;
      }
    }
    .approval-bottom {
      position: fixed;
      bottom: 50px;
      left: 48%;
      // margin-top: 30px;
      // margin-bottom: 20px;
      text-align: center;
    }
  }
  .footer_btn {
    position: absolute;
    bottom: 50px;
    left: 40%;
  }
}
</style>
